<?php
namespace App\Supports\File;

use Intervention\Image\Constraint;
use Illuminate\Support\Facades\File;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;

class ImageUploader
{
	/**
	 * @var \Intervention\Image\Image
	 */
	protected $image;
	protected $imageName = '';
	protected $imageExtension = '';
	protected $imageFullName = '';
	
	protected $maxWidth = 1080;
	protected $maxHeight = 1080;
	
	protected function setProperties($image)
	{
		$this->image = Image::make($image);
		$this->imageName = uniqid(time());
		$this->imageExtension = $image->extension();
		$this->imageFullName = "{$this->imageName}.{$this->imageExtension}";
		
		if (! File::isDirectory(public_path('temp'))) {
			File::makeDirectory(public_path('temp'), 755, true, true);
		}
	}
	
	protected function localFolderPath()
	{
		return public_path("temp");
	}
	
	protected function localFullPath()
	{
		return public_path("temp/{$this->imageFullName}");
	}
	
	protected function remoteFolderPath()
	{
		return "uploads/images/" . date("Ym/d", time());
	}
	
	protected function remoteFullPath()
	{
		return "{$this->remoteFolderPath()}/{$this->imageFullName}";
	}
	
	protected function saveToLocal()
	{
		$width = $this->image->width();
		$height = $this->image->height();
		if ($width > $this->maxWidth) {
			$this->image->resize($this->maxWidth, null, function (Constraint $constraint) {
				$constraint->aspectRatio();
				$constraint->upsize();
			});
		}
		if ($height > $this->maxHeight) {
			$this->image->resize(null, $this->maxHeight, function (Constraint $constraint) {
				$constraint->aspectRatio();
				$constraint->upsize();
			});
		}
		$this->image->save($this->localFullPath());
	}
	
	protected function saveToRemote()
	{
		Storage::putFileAs($this->remoteFolderPath(), $this->localFullPath(), $this->imageFullName);
		File::delete($this->localFullPath());
		return Storage::url($this->remoteFullPath());
	}
	
	protected function save()
	{
		$this->saveToLocal();
		return $this->saveToRemote();
	}
	
	public function upload($image)
	{
		$this->setProperties($image);
		return $this->save();
	}
}
